package it.itsvil.servlet;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.jms.ObjectMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class XMLServlet
 */
public class XMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ServletContext servletContext = null;

	private static final String TMP_DIR_PATH = "/opt/jboss-5.1.0.GA/tmp";
	private static final String DESTINATION_DIR_PATH = "/opt/jboss-5.1.0.GA/upload";

	private File tmpDir;
	private File destinationDir;
	private String realPath;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public XMLServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	private Properties getInitialContextProps() {
		Properties props = new Properties();
		props.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,
				"org.jboss.naming:org.jnp.interfaces");
		props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		props.put(Context.SECURITY_PRINCIPAL, "admin");
		props.put(Context.SECURITY_CREDENTIALS, "admin");
		return props;
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		realPath = new String(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List<?> items = uploadHandler.parseRequest(request);
			Iterator<?> itr = items.iterator();
			// DiscoveryConfig config = new DiscoveryConfig();

			File file = null;
			if (itr.hasNext()) {
				FileItem fi = (FileItem) itr.next();
				file = new File(destinationDir, UUID.randomUUID().toString());
				fi.write(file);
			}

			System.out.println("File upload started successfully");
			String parser = request.getParameter("parser");
			System.out.println(parser);
			try {
				System.out.println("sendReceiveTopic");
				Context initial = new InitialContext(getInitialContextProps());
				TopicConnectionFactory tcf = (TopicConnectionFactory) initial
						.lookup("ConnectionFactory");
				TopicConnection conn = tcf.createTopicConnection();
				Topic topic = (Topic) initial.lookup("MyTopic");
				TopicSession session = conn.createTopicSession(false,
						TopicSession.AUTO_ACKNOWLEDGE);

				conn.start();
				TopicPublisher send = session.createPublisher(topic);
				ObjectMessage om = session.createObjectMessage();

				if (request.getParameter("parser") == "1") {

					om.setStringProperty("parser", "XLST");
				} else {
					om.setStringProperty("parser", "XQuery");
				}
				om.setStringProperty("filePath", file.toString());
				om.setObject(file);
				send.publish(om);
				System.out.println("Message object published on topic");

				send.close();
				conn.stop();
				session.close();
				conn.close();
				initial.close();
				File htmlFile = new File(file.toString() + ".html");
				Thread.currentThread();
				Thread.sleep(5000);
				Desktop.getDesktop().browse(htmlFile.toURI());

			} catch (InterruptedException e) {

			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		out.close();
	}
}
